/**
 * 
 */
package com.cgbsoft.financial;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.cgbsoft.financial.common.ConfigurationManager;
import com.cgbsoft.financial.dao.CacheTransactionDB;
import com.cgbsoft.financial.dao.MyTransactionDB;
import com.cgbsoft.financial.domain.MyTransaction;
import com.cgbsoft.financial.utils.DateUtil;

/**
 * @author CX
 *
 */
public class TransactionAdd extends Activity {
	
	static final int DATE_DIALOG_ID = 0; 
	static final int AUTOCOMPLETE_TEXT_ID = 0; 
	
	private EditText transactionSummary, transactionMoney;
	private TextView transactiondate, transactionCatagory;
	private LinearLayout autoCompleteLayout;
	private Button transationAddButton;
	private Button transationCancelButton;
	private RadioGroup transactionType;
	
	String[] outcomeselectOptionList={"日常", "生活", "节日", "娱乐", "家庭", "教育", "其他"};
	String[] incomeSelectOptionList={"工资", "奖金", "提成", "报销", "营业", "分红", "股票", "基金", "利息", "其他"};
	
	//缓存到数据库中的帐单，输入时选择根据
	private static List<MyTransaction> cacheTransactionList = new ArrayList<MyTransaction>();
	
	public ProgressDialog pd_loading;//进度条对话框
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.transaction_add);
        
        transactiondate = (TextView)findViewById(R.id.transaction_date);
        transactionSummary = (EditText)findViewById(R.id.transaction_summary);
        transactionMoney = (EditText)findViewById(R.id.transaction_money);
        transactionType = (RadioGroup)findViewById(R.id.transaction_type);
        transationAddButton = (Button)findViewById(R.id.transation_add_button);
        transationCancelButton = (Button)findViewById(R.id.transation_cancel_button);
        transactionCatagory = (TextView)findViewById(R.id.transaction_catagory);
        autoCompleteLayout = (LinearLayout)findViewById(R.id.auto_completeLayout);
        
        transactiondate.setOnClickListener(clickListener);
        transationAddButton.setOnClickListener(clickListener);
        transationCancelButton.setOnClickListener(clickListener);
        transactionCatagory.setOnClickListener(clickListener);
        
        transactionSummary.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable editable) {
				initCacheData();//每输入一个字都更新一次自动完成的常用帐单
			}
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });
        transactionSummary.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					initCacheData();//显示时更新自动完成数据
				} else {
					autoCompleteLayout.setVisibility(View.GONE);
				}
			}
        });
        
        transactionType.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(RadioGroup arg0, int checkId) {
				switch(checkId) {
				case R.id.outcome:
					transactionType.setTag(((RadioButton) findViewById(R.id.outcome)).getText().toString());
					transactionCatagory.setText(outcomeselectOptionList[0]);
					break;
				case R.id.income:
					transactionType.setTag(((RadioButton) findViewById(R.id.income)).getText().toString());
					transactionCatagory.setText(incomeSelectOptionList[0]);
					break;
				default:
					break;
				}
			}
    	});
        ((RadioButton) findViewById(R.id.outcome)).setChecked(true);//默认是支出
        
        //初始化数据
        transactiondate.setText(DateUtil.getDate());
        
        pd_loading = new ProgressDialog(this);
		pd_loading.setCancelable(true);
    }
    
    
    
    private void addTransation() {
    	
    	final String transactiondateValue = transactiondate.getText().toString();
    	final String transactionSummaryValue = transactionSummary.getText().toString();
		String transactionMoneyValue = transactionMoney.getText().toString();
		final String transactionTypeValue = transactionType.getTag().toString();
		final String transactionCatagoryValue = transactionCatagory.getText().toString();
		
		try {
			new BigDecimal(transactionMoneyValue);
		} catch (Exception e) {
			Toast.makeText(this, "金额中请输入整数。", Toast.LENGTH_SHORT).show();
			return;
		}
		
		transactionMoneyValue = new BigDecimal(transactionMoneyValue).multiply(new BigDecimal("100")).toString();
		
		MyTransaction newTransaction = new MyTransaction();
		newTransaction.setdDate(transactiondateValue);
		newTransaction.setsSubject(transactionSummaryValue);
		newTransaction.setiSum(("收入".equalsIgnoreCase(transactionTypeValue) ? "+" : "-") + transactionMoneyValue);
		newTransaction.setcCatagory(transactionCatagoryValue);
    	
		if (transactionMoneyValue != "" && transactionSummaryValue != "") {
			addTransactionToXml(newTransaction);
		}
    }
    
    private void addTransactionToXml(final MyTransaction newTransaction) {
    	pd_loading.setMessage("添加中...");
    	pd_loading.show();
    	new Thread(
				new Runnable() { 
					public void run() { 
						boolean returnInd = false;
						CacheTransactionDB.saveOrUpdateMyTransaction(TransactionAdd.this, newTransaction);//缓存常用记录
						
						if (ConfigurationManager.getInstance(TransactionAdd.this).getBooleanConfig(ConfigurationManager.IF_DB_STORE, false)) {
							//添加到数据库
							MyTransactionDB.insertMyTransaction(TransactionAdd.this, newTransaction);
							returnInd = true;
						} else {
							//添加到xml中去
					        SAXReader reader = new SAXReader();
					        try {
					            Document document = reader.read(new File(FinancialActivity.transactionFilePath));

					            //在DataSet1元素中增加MyTransaction元素
					            List list = document.selectNodes("/DataSet1");
					            Iterator itr = list.iterator();
					            if(itr.hasNext()) {
					                Element dataSet1Element = (Element)itr.next();
					                Element myTransactionElement = dataSet1Element.addElement("MyTransaction");
					                
					                Element idElement = myTransactionElement.addElement("ID");
					                idElement.setText(String.valueOf(FinancialActivity.lastTransactionId + 1));

					                Element dDateElement = myTransactionElement.addElement("d_Date");
					                dDateElement.setText(newTransaction.getdDate());
					                
					                Element iSumElement = myTransactionElement.addElement("i_Sum");
					                iSumElement.setText(newTransaction.getiSum());
					                
					                Element sSubjectElement = myTransactionElement.addElement("s_Subject");
					                sSubjectElement.setText(newTransaction.getsSubject());
					                
					                Element cCatagoryElement = myTransactionElement.addElement("c_Catagory");
					                cCatagoryElement.setText(newTransaction.getcCatagory());
					            }
					            
					            //输出
					            XMLWriter output;
					            OutputFormat format = OutputFormat.createPrettyPrint();
				                output = new XMLWriter(new FileWriter(FinancialActivity.transactionFilePath), format);
				                output.write(document);
				                output.close();
				                returnInd = true;
					        } catch (DocumentException e) {            
					            e.printStackTrace();
					        } catch (IOException e) {
				                e.printStackTrace();
				            }
						}
				        
				        if (pd_loading.isShowing()) {
				        	pd_loading.dismiss();
				        }
				        
				        //跳回主界面
				        if (returnInd) {
							TransactionAdd.this.finish();
				        }
					} 
				}).start();	
    }
    
    OnClickListener clickListener= new OnClickListener() { 
    	@Override
    	public void onClick(View v) { 
    		switch (v.getId()) {
    		case R.id.transaction_catagory:{
    			String[] tempOptionList = outcomeselectOptionList;
    			if ("收入".equalsIgnoreCase(transactionType.getTag().toString())) {
    				tempOptionList = incomeSelectOptionList;
    			}
    			final String[] selectOptionList = tempOptionList;
	  	          new AlertDialog.Builder(TransactionAdd.this)
	  	            .setTitle("类别选择")
	  	            .setItems(
	  	            		selectOptionList,
	  	            		new DialogInterface.OnClickListener() {
			    	              public void onClick(DialogInterface dialog, int whichItem) {                                      
			    	            	  transactionCatagory.setText(selectOptionList[whichItem]);
			    	              }
			    	            })
	  	            .setNegativeButton(
	  	            		"取消", 
	  	            		new DialogInterface.OnClickListener() { 
			    	              public void onClick(DialogInterface d, int which) { 
			    	                d.dismiss(); 
			    	              }
			    	            })
	  	            .show();
	  	          break;
    		}
    		case R.id.transaction_date: {//日期选择
    			showDialog(DATE_DIALOG_ID);
    			break;
    		}
    		case R.id.transation_add_button: {//添加消费
    			addTransation();
    	         break;
    			}
    		case R.id.transation_cancel_button: {
    			TransactionAdd.this.finish();
    			break;
    		}
    		case AUTOCOMPLETE_TEXT_ID: {
    			Object tag = v.getTag();
    			if (v != null) {
    				MyTransaction transaction = (MyTransaction) tag;
    				//设置缓存的内容，日期不设置
    				String money = transaction.getiSum();
    				transactionSummary.setText(transaction.getsSubject());
    	            transactionMoney.setText(money.substring(1, money.length() -2));
    	            transactionCatagory.setText(transaction.getcCatagory());
    	            if ('+' == money.charAt(0)) {
    	            	transactionType.setTag(((RadioButton) findViewById(R.id.income)).getText().toString());
    	            	((RadioButton) findViewById(R.id.income)).setChecked(true);
    	        	} else {
    	        		transactionType.setTag(((RadioButton) findViewById(R.id.outcome)).getText().toString());
    	        		((RadioButton) findViewById(R.id.outcome)).setChecked(true);
    	        	}
    			}
    			break;
    		}
    		default:
    			break;
    		}
    		
    	}
	};
	
	//日期选择
	@Override    
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID: 
        	String tday = transactiondate.getText().toString();
            return new DatePickerDialog(this,     
                        mDateSetListener,   
                        Integer.valueOf(tday.substring(0, 4)), 
                        Integer.valueOf(tday.substring(5, 7)) - 1, 
                        Integer.valueOf(tday.substring(8, 10)));     
        }
        return null;
    } 
	
	//点击事件
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { 
        public void onDateSet(DatePicker view, int year,      
                              int monthOfYear, int dayOfMonth) {    
            transactiondate.setText(year + "-" + (monthOfYear > 8 ? (monthOfYear+1) : ("0"+(monthOfYear+1))) + "-" + (dayOfMonth > 9 ? dayOfMonth : ("0"+dayOfMonth)));
        }
    };
    
    /**
     * 从数据库读取常用记录
     */
    private void initCacheData() {
    	new Thread(new Runnable() {
			@Override
			public void run() {
				String inputSubject = transactionSummary.getText() != null ? transactionSummary.getText().toString() : "";
				//读取缓存列表
				TransactionAdd.cacheTransactionList = CacheTransactionDB.findMyTransactionsBySubect(TransactionAdd.this, inputSubject);
				
				Log.i("initCacheData", "cacheTransactionList: "+cacheTransactionList.size());
				Message message=new Message();
				message.what=0;
				mHandler.sendMessage(message);
			}
		}).start();
    }
    
    Handler mHandler=new Handler(new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				//显示常用主题
				autoCompleteLayout.removeAllViews();
				if (cacheTransactionList.size() == 0) {
					autoCompleteLayout.addView(createTextView("暂无常用摘要。", null));
				} else {
					autoCompleteLayout.addView(createTextView("常用摘要：", null));
					for (MyTransaction transaction : cacheTransactionList) {
						autoCompleteLayout.addView(createTextView(transaction.getsSubject(), transaction));
					}
				}
				autoCompleteLayout.setVisibility(View.VISIBLE);//显示出来
				break;
			default:
				break;
			}
			return false;
		}
    });
    
    /**
     * 创建自动完成的提示TextView，统一ID设置点击事件，如果有tag的，就进行设置
     * @param text
     * @param tag
     * @return
     */
    private TextView createTextView(String text, Object tag) {
    	TextView textView = new TextView(TransactionAdd.this);
    	textView.setId(AUTOCOMPLETE_TEXT_ID);
    	textView.setTextSize(16f);
		textView.setText(text);
		textView.setOnClickListener(clickListener);
		if (tag != null) {
			textView.setTag(tag);
		}
		textView.setPadding(10, 0, 0, 0);
		return textView;
    }
    
}
